<?php

/**
 * Description of Image
 *
 * @author Kam
 */
class Application_Model_DAO_Image extends My_DAO_Abstract {

    const DB_IMAGE = 'Image';

    public function update(array $data, $whereOrId) {
        return $this->getDbTable()->update($data, $whereOrId);
    }


    public function delete($ids, $column = 'image_id') {
        if (!is_array($ids)) {
            if(empty($ids)) {
                return ;
            }
            $ids = array($ids);
        }
        if (empty($ids)) {
            return;
        }
        $where = $this->quoteInto($column . ' IN (?)', $ids);
        $imgs = $this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
                        ->where($where)
                        ->query()->fetchAll();
        foreach ($imgs as $img) {
            $code = $img['code'];
            My_Utils::removeFileOrDir(My_Utils::getImageUploadedPath() . '/' . $code . '.jpg');
            My_Utils::removeFileOrDir(My_Utils::getImagePublicCachePath() . '/' . $code);
        }
        return $this->getDbTable()->delete($where);
    }

    public function addNew($path, $data) {
        if (!isset($data['filename']) || empty($data['filename'])) {
            $fileName = pathinfo($path, PATHINFO_BASENAME);
            $data['filename'] = $fileName;
        }

        $imageId = $this->getDbTable()->insert($data);

        $image = $this->getDbTable()->get($imageId);

        $code = $image['code'];
        $destPath = realpath(APPLICATION_PATH . '/../uploaded/image');
        $destPath .= '/' . $code . '.jpg';
        if (@rename($path, $destPath)) {
            $image['path'] = $destPath;
            return $image;
        } else {
            $this->getDbTable()->delete((int) $imageId);
            return null;
        }
    }

    protected function getDbTableNameMap() {
        return array(
            self::DB_IMAGE => 'Application_Model_DbTable_Image',
        );
    }

    protected function getDefaultDbTableName() {
        return self::DB_IMAGE;
    }

}
